package com.xigege.netty.TCPStickyBag.solve.fixedLength;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * @author huangxi
 * @class StickHalfBagClient
 * @description StickHalfBagClient
 * @create 2022-08-23 15:03
 */
public class FixedLengthClient {

    public static byte[] fill10Bytes(char c, int len) {
        StringBuilder sb = new StringBuilder(10);
        for (int i = 0; i < len; i++) {
            sb.append(c);
        }
        for (int j = 0; j < 10 - len; j++) {
            sb.append("_");
        }
        return sb.toString().getBytes();
    }

    public static void main(String[] args) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ChannelFuture future = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                // 连接建立好之后
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    char c = '5';
                                    for (int i = 0; i < 10; i++) {
                                        ByteBuf buffer = ctx.alloc().buffer();
                                        buffer.writeBytes(fill10Bytes(c, new Random().nextInt(10) + 1));
                                        c++;
                                        ctx.writeAndFlush(buffer);
                                    }
                                    super.channelActive(ctx);
                                }
                            });
                        }
                    })
                    .connect(new InetSocketAddress("localhost", 6666))
                    .sync();
            Channel channel = future.channel();
            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}
